package com.hyfrogx.modules.app.controller.information;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.param.JSONResult;
import com.hyfrogx.common.qcloud.UploadUtils;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.modules.app.annotation.Login;
import com.hyfrogx.modules.app.entity.HyUserAttentionEntity;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.form.information.CommentForm;
import com.hyfrogx.modules.app.form.information.MediaNameForm;
import com.hyfrogx.modules.app.form.information.ReplyCommentForm;
import com.hyfrogx.modules.app.form.information.VerifyMediaForm;
import com.hyfrogx.modules.app.service.AttentionService;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.app.utils.FrogxTaskCode;
import com.hyfrogx.modules.app.utils.StringUtils;
import com.hyfrogx.modules.information.entity.*;
import com.hyfrogx.modules.information.service.*;
import com.hyfrogx.modules.manage.service.HyPayRecordService;
import com.hyfrogx.modules.manage.service.task.TaskService;
import com.hyfrogx.modules.sys.entity.SysUserEntity;
import com.hyfrogx.modules.sys.service.SysUserRoleService;
import com.hyfrogx.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author liubin
 * @date 2019/10/22 17:25
 */
@RestController
@RequestMapping("api/information")
@Api(value = "ApiInformationController", tags = {"客户端--资讯模块"})
public class ApiInformationController {
  @Autowired
  private HyInformationVerifyService informationVerifyService;
  @Autowired
  private AttentionService attentionService;
  @Autowired
  private InfoImgService infoImgService;
  @Autowired
  private HyInformationOrderService orderService;
  @Autowired
  private UserService userService;
  @Autowired
  private HyPayRecordService payRecordService;
  @Autowired
  private InformationService informationService;
  @Autowired
  private HyVerifyPriceService verifyPriceService;
  @Autowired
  private InformationClassifyService informationClassifyService;
  @Autowired
  private InfoCommentService infoCommentService;
  @Autowired
  private InfoCommentReplyService infoCommentReplyService;
  @Autowired
  private SysUserService sysUserService;
  @Autowired
  private SysUserRoleService userRoleService;
  @Autowired
  TaskService taskService;
  /**
   * 编辑图片上传
   *
   * @return
   */
  @RequestMapping(value = "verify/uploadimg", method = RequestMethod.POST)
  @ApiOperation("编辑图片上传")
  public R uploadImg(@RequestParam("file") MultipartFile file) {
    String result = null;
    if (file != null) {
      String fileName = UUID.randomUUID().toString() + file.getOriginalFilename()
        .substring(file.getOriginalFilename()
          .lastIndexOf("."), file.getOriginalFilename().length());
      result = UploadUtils.upload(UploadUtils.convertFile(file), fileName, FrogConstant.Path.INFORMATION_VERIFY_FU);
    }
    return R.ok(result);
  }

  /**
   * 获取所有分类
   *
   * @return
   */
  @RequestMapping(value = "getAllClassify", method = RequestMethod.GET)
  @ApiOperation("获取所有资讯分类")
  public R getAllClassify() {
    return R.ok().put("data", informationClassifyService.getAllClassifyForApi());
  }


  /**
   * @param userId
   * @param form
   * @return
   */
  @RequestMapping(value = "verify/commit", method = RequestMethod.POST)
  @Login
  @ApiOperation("新建资讯号审核")
  public R verifyInformations(@ApiIgnore @RequestAttribute("userId") Long userId, @RequestBody VerifyMediaForm form) {
    // 是否存在过审核
    int result = informationVerifyService.getBaseMapper()
      .selectCount(new QueryWrapper<HyInformationVerifyEntity>().eq("uid", userId));
    if (result > 1) {
      return R.error("数据重复");
    }

    //初始化资讯号订单
    HyInformationOrderEntity order = new HyInformationOrderEntity();
    // 新用户
    if (result == 0) {
      // 校验用户名公司是否为空
      if (StringUtils.isBlank(form.getUserName())) {
        return R.error("用户名不可以为空");
      }
      if (StringUtils.isBlank(form.getCompanyName())) {
        return R.error("公司名不可以为空");
      }
      // 是否有过订单-是，return
      int orderResult = orderService.getBaseMapper()
        .selectCount(new QueryWrapper<HyInformationOrderEntity>().eq("uid", userId));
      if (orderResult > 0) {
        return R.error("非新用户");
      }
      if (orderResult > 1) {
        return R.error("数据重复");
      }

      // 获取配置定价
      HyVerifyPriceEntity verifyPrice = verifyPriceService.getBaseMapper().selectOne(new QueryWrapper<>());
      if (ObjectUtil.isNull(verifyPrice)) {
        return R.error("配置定价异常");
      } else {
        int price = verifyPrice.getTrueprice();
        order.setPaidPrice(price);
        order.setProductPrice(price);
      }
      // 钱是否足够-否，return
      //userService.reduce(order.getUid(), order.getProductprice());
      //不是一键哥不需要传授权书
      if (form.getIsYiJianGe() == FrogConstant.InformationVerify.NOTYIJIANGE) {
        form.setPowerOfAttorneyImg(null);
      }

      // 生成订单号
      order.setOrderId(orderService.createOrderId());
      // 创建订单，审核记录，消费记录
      order.setUid(userId);

      if (orderService.getBaseMapper().insert(order) < 1) {
        return R.error("创建订单失败");
      }
      if (informationVerifyService.commitVerify(form, userId) < 1) {
        return R.error("创建审核记录失败");
      }
      if (payRecordService.addInformationOrder(order) > 0) {
        return R.ok("成功提交审核");
      }
    }

    // 老用户
    if (result == 1) {
      HyInformationVerifyEntity record = informationVerifyService.getVerifyRecordByUid(userId.intValue());
      // 查询审核状态012
      // 审核状态拒绝
      if (record.getVerifyStatus() == FrogConstant.InformationVerify.REJECT) {
        // 校验用户名公司名是否除了自己重复
        // 不是一键哥授权书不传
        if (form.getIsYiJianGe() == FrogConstant.InformationVerify.NOTYIJIANGE) {
          form.setPowerOfAttorneyImg(null);
        }
        int id = record.getId();
        record = new HyInformationVerifyEntity();
        record.setId(id);
        record.setVerifyStatus(FrogConstant.InformationVerify.PENDING);
        BeanUtils.copyProperties(form, record);
        if (informationVerifyService.getBaseMapper().updateById(record) > 0) {
          return R.ok("成功更新审核");
        }
      }
      // 审核状态通过
      if (record.getVerifyStatus() == FrogConstant.InformationVerify.PASS) {
        // 是否存在过订单-否，return
        int orderResult = orderService.getBaseMapper()
          .selectCount(new QueryWrapper<HyInformationOrderEntity>().eq("uid", userId));
        if (orderResult < 1) {
          return R.error("非老用户");
        }
        if (orderResult > 1) {
          return R.error("数据重复");
        }
        // 获取配置定价
        HyVerifyPriceEntity verifyPrice = verifyPriceService.getBaseMapper().selectOne(new QueryWrapper<>());
        if (verifyPrice == null) {
          return R.error("配置定价异常");
        } else {
          int price = verifyPrice.getTrueprice();
          order.setPaidPrice(price);
          order.setProductPrice(price);
        }
        // 是否余额够
        userService.reduce(order.getUid(), order.getProductPrice());
        // 是否到当前时间毫秒数大于到期时间
        if (System.currentTimeMillis() > order.getExpireDate().getTime()) {
          // 校验用户名公司名是否除了自己重复
          // 是否一键哥
          if (form.getIsYiJianGe() == FrogConstant.InformationVerify.NOTYIJIANGE) {
            form.setPowerOfAttorneyImg(null);
          }
          // 重置审核通过时间null
          // order.setVerifydate(null);
          // 创建订单，审核记录，消费记录
          order.setCreateTime(new Date());
          if (orderService.getBaseMapper().insert(order) < 1) {
            return R.error("创建订单失败");
          }
          if (informationVerifyService.commitVerify(form, userId) < 1) {
            return R.error("创建审核记录失败");
          }
          if (payRecordService.addInformationOrder(order) > 0) {
            return R.ok("成功更新提交审核");
          }
        }
      }
    }
    return R.error("审核异常");
  }



  /**
   * 资讯首页（已关注）
   *
   * @return
   */
  @RequestMapping(value = "getallFollowRecord", method = RequestMethod.GET)
  @Login
  @ApiOperation("资讯首页（已关注）")
  public R getAllFollowRecordClient(@ApiIgnore @RequestAttribute("userId") Long userId, @RequestParam Map<String, Object> map) {
    try {
      map.put("fid",userId);
      // 查询用户的所有关注列表
      List<HyUserAttentionEntity> attentionResult = attentionService.getAllFollowId(userId);
      // 后台所有推荐的资讯号的uname,head
      List<HyInformationVerifyEntity> recommendResult = informationVerifyService.getAllRecommendReordClient();
      // 遍历所有的recommendResult
      if (recommendResult != null) {
        for (HyInformationVerifyEntity recommended : recommendResult) {
          for (HyUserAttentionEntity a : attentionResult) {
            if (recommended.getUid().equals(a.getSid())) {
              recommended.setIsfollow(1);
            }
          }
        }
      }

      // 后台所有显示最新有资讯更新的5个（看一行能排列几个），如果都没有更新，就显示最新关注的6个
      HyInformationVerifyEntity v = new HyInformationVerifyEntity();
      v.setFid(userId.intValue());
      List<HyInformationVerifyEntity> result = informationVerifyService.getAllFollowRecordClient1(v.getFid());

      // 关注过的资讯号的资讯列表,显示关注过的资讯号，最新发布的资讯 待优化
      Page page = informationVerifyService.getAllFollowRecordClient(new QueryExt<>(map));
      List<HyInformationVerifyEntity> information = page.getRecords();
      if (information.size() > 0) {
        for (HyInformationVerifyEntity informationResult : information) {
          List<InfoImgEntity> imglist = infoImgService.getBaseMapper()
            .selectList(new QueryWrapper<InfoImgEntity>().eq("info_id", informationResult.getMid()));
          informationResult.setInfoImgList(imglist);
          informationResult.setImgnum(imglist.size());
        }
      }

      map.put("recommendResult", recommendResult);
      map.put("followResult", result);
      map.put("followInformation", information);
      map.put("total",page.getTotal());
      map.put("size",page.getSize());
      map.put("current",page.getCurrent());
      map.put("pages",page.getPages());
      map.put("searchCount",true);
      return R.ok().put("data", map);
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 查询资讯号审核反馈
   *
   * @return
   */
  @RequestMapping(value = "verify/feedback", method = RequestMethod.POST)
  @Login
  @ApiOperation("查询资讯号审核反馈")
  public R getVerifyFeedback(@ApiIgnore @RequestAttribute("userId") Long userId) {
    try {
      HyInformationVerifyEntity verifyEntity = informationVerifyService.getBaseMapper()
        .selectOne(new QueryWrapper<HyInformationVerifyEntity>()
          .eq("uid", userId));
      if (ObjectUtil.isEmpty(verifyEntity)) {
        HyInformationVerifyEntity record = new HyInformationVerifyEntity();
        record.setVerifyStatus(FrogConstant.InformationVerify.NOTSUBMIT);
        return R.ok().put("data", record);
      }

      if (verifyEntity.getVerifyStatus() == FrogConstant.InformationVerify.PASS) {
        verifyEntity.setWebsite("http://wuxiheyoo.com");
        HyInformationOrderEntity o = orderService.getBaseMapper()
          .selectOne(new QueryWrapper<HyInformationOrderEntity>()
            .eq("uid", userId));

        if (o == null) {
          verifyEntity.setVerifyStatus(FrogConstant.InformationVerify.PASS);
          DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          Date date = dateFormat2.parse("2028-10-25 06:06:06");
          verifyEntity.setExpiredate(date);
          return R.ok().put("data", verifyEntity);
        }
        // 如果当前审核通过但是超过到期时间
        // 已过期需重新认证
        verifyEntity.setExpiredate(o.getExpireDate());
        if (System.currentTimeMillis() > o.getExpireDate().getTime()) {
          verifyEntity.setExpiredate(o.getExpireDate());
          verifyEntity.setVerifyStatus(FrogConstant.InformationVerify.EXPIRE);
          return R.ok().put("data", verifyEntity);
        }
      }
      return R.ok().put("data", verifyEntity);
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 查询用户是否有关注过资讯号
   */
  @RequestMapping(value = "isFollowNull", method = RequestMethod.POST)
  @ApiOperation("查询用户是否有关注过资讯号")
  @Login
  public R isFollowNull(@ApiIgnore @RequestAttribute("userId") Long userId) {
    try {
      int result = userService.getIsFollowNull(userId.intValue());
      if (result == 0) {
        return R.ok().put("data", 0);
      }
      return R.ok().put("data", 1);
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 校验名称
   *
   * @return
   */
  @RequestMapping(value = "verify/name", method = RequestMethod.POST)
  @ApiOperation("校验名称")
  @Login
  public R verifyName(@ApiIgnore @RequestAttribute("userId") Long userId, @RequestBody MediaNameForm form) {
    try {
      if (StringUtils.isBlank(form.getUserName()) || StringUtils.isBlank(form.getCompanyName())) {
        return R.error("公司名和用户名不能为空");
      }
      // 是否存在该用户的认证信息
      int isHave = informationVerifyService.getBaseMapper()
        .selectCount(new QueryWrapper<HyInformationVerifyEntity>().eq("uid", userId));
      if (isHave > 1) {
        return R.error("数据重复");
      }
      int duplicateName = sysUserService.getBaseMapper()
        .selectCount(new QueryWrapper<SysUserEntity>().eq("username",form.getCompanyName()).eq("app_uid",userId));
      if (duplicateName>0){
        return R.error("系统用户已存在该公司名");
      }
      if (isHave == 1) {
        // 存在 ,取原对象过滤
        HyInformationVerifyEntity hyInformationVerify = informationVerifyService.getVerifyRecordByUid(userId.intValue());
        if (!hyInformationVerify.getUserName().equals(form.getUserName())) {
          // 如果此用户不是已提交审核的用户
          HyInformationVerifyEntity nameRecord = informationVerifyService.getBaseMapper()
            .selectOne(new QueryWrapper<HyInformationVerifyEntity>()
              .eq("user_name", form.getUserName()).select("uid"));
          if (nameRecord != null) {
            return R.error("此用户名已有人使用");
          }
        }
        if (!hyInformationVerify.getCompanyName().equals(form.getCompanyName())) {
          HyInformationVerifyEntity companynameRecord = informationVerifyService.getBaseMapper()
            .selectOne(new QueryWrapper<HyInformationVerifyEntity>()
              .eq("company_name", form.getCompanyName()).select("uid"));
          if (companynameRecord != null) {
            return R.error("此公司名已有人使用");
          }
        }
      } else {
        // 不存在
        // 如果此用户不是已提交审核的用户
        HyInformationVerifyEntity nameRecord = informationVerifyService.getBaseMapper()
          .selectOne(new QueryWrapper<HyInformationVerifyEntity>()
            .eq("user_name", form.getUserName()).select("uid"));
        if (nameRecord != null) {
          return R.error("此用户名已有人使用");
        }
        HyInformationVerifyEntity companynameRecord = informationVerifyService.getBaseMapper()
          .selectOne(new QueryWrapper<HyInformationVerifyEntity>()
            .eq("company_name", form.getCompanyName()).select("uid"));
        if (companynameRecord != null) {
          return R.error("此公司名已有人使用");
        }

      }
      return R.ok();
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 用户对资讯点赞 需要参数 infoId，uid
   *
   * @return
   */
  @RequestMapping(value = "likeInformations", method = RequestMethod.GET)
  @Login
  @ApiOperation("点赞资讯")
  public R likeInformations(@ApiIgnore @RequestAttribute("userId") Long userId, Integer infoId) {
    try {
      //查询某个人对某条资讯点赞多少次
      int i = infoCommentService.getBaseMapper()
        .selectCount(new QueryWrapper<InfoCommentEntity>().eq("uid", userId).eq("info_id", infoId));
      if (i > 0) {
        return R.error("请勿重复点赞");
      } else {
        InfoCommentEntity commentEntity = new InfoCommentEntity();
        commentEntity.setUid(userId.intValue());
        commentEntity.setInfoId(infoId);
        infoCommentService.getBaseMapper().insert(commentEntity);
        return R.ok("点赞成功");
      }
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 用户评论资讯 需要参数 infoId，comment
   *
   * @return
   */
  @RequestMapping(value = "commectInformation", method = RequestMethod.POST)
  @Login
  @ApiOperation("资讯评论")
  public R commectInformation(@ApiIgnore @RequestAttribute("userId") Long userId, @RequestBody CommentForm form) {

    InfoCommentEntity infoComment = new InfoCommentEntity();
    BeanUtils.copyProperties(form,infoComment);
    infoComment.setUid(userId.intValue());
    if (infoCommentService.commectInformation(infoComment) > 0) {
      try {
        taskService.taskRemark(userId, FrogxTaskCode.TaskCode.REMAKE_TEXT,infoComment.getId());
        return R.ok("评论成功");
      }catch (ServiceException e){
        return R.ok("评论成功");
      }catch (Exception e){
        return R.error(e.getMessage());
      }
    }
    return R.error("评论失败");
  }

  /**
   * 用户二级评论资讯 需要参数 infoId，comment
   *
   * @return
   */
  //@RequestMapping(value = "CommentReplyInformation", method = RequestMethod.POST)
  @Login
  @ApiOperation("二级评论")
  @PostMapping("CommentReplyInformation")
  public R CommentReplyInformation(@ApiIgnore @RequestAttribute("userId") Long userId, @RequestBody ReplyCommentForm form) {
    InfoCommentReplyEntity infoCommentReply = new InfoCommentReplyEntity();
    BeanUtils.copyProperties(form,infoCommentReply);
    infoCommentReply.setState(1);
    infoCommentReply.setCreated(new Date());
    infoCommentReply.setUid(userId.intValue());
    infoCommentReplyService.getBaseMapper().insert(infoCommentReply);
    return R.ok("评论成功");
  }


  /**
   * 资讯详情
   *
   * @param id
   * @return
   */
  @RequestMapping(value = "information/getInformationById", method = RequestMethod.GET)
  @ApiOperation("资讯详情")
  @Login
  public R getInformationById(Integer id) {
    try {
      HyInformationEntity result = informationService.getInformationById(id,FrogConstant.Role.APPUSER);
      result.setDisclaimer("用户在三眼蛙发表的内容仅表明其个人的立场和观点，并不代表三眼蛙的立场或观点。");

      // 格式化
      SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      if (result.getPublishTime() != null) {
        String sDate = sdfa.format(result.getPublishTime());
        result.setNDate(this.Calculation(sDate));
        // result.setNdate(sDate.toString().substring(0, 10));
      }
      // 获取用户账号
      String account = result.getPublisher();
      // 根据账号获取用户头像
      User user = userService.getBaseMapper()
        .selectOne(new QueryWrapper<User>()
          .eq("account", account)
          .select("uid", "username", "head"));
      if (user != null) {
        // 判断用户role,是普通用户还是资讯号,资讯号取认证信息的logo和用户名称
        Integer roleId = userRoleService.selectByAppUid(user.getUid().intValue());
        if (roleId == FrogConstant.Role.MEDIA) {
          HyInformationVerifyEntity v = informationVerifyService.getAccountByUid(user.getUid());
          // 如果是资讯号,获取认证的用户名称和简介
          user.setUsername(v.getUserName());
          user.setSignature(v.getAuthenticationInformation());
        }
        result.setUser(user);
        return R.ok().put("data", result);
      }
      if(result.getCommentCount()==null){
        result.setCommentCount(0);
      }
      return R.ok().put("data", result);
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }


  public String Calculation(String time) throws Exception {
    // 定义返回值
    String ndate = "";
    // 格式化
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = format.parse(time);
    long oldMls = date.getTime() / 1000;

    long nowMls = System.currentTimeMillis() / 1000;

    long cell = nowMls - oldMls;

    // 小于一分钟。 --- 刚刚
    if (cell < 60) {
      ndate = "刚刚";
    }
    // 一分钟以上60分钟内
    if (cell > 60 && cell < 3600) {
      ndate = cell / 60 + "分钟前";
    }
    // 一小时以上24小时内
    if (cell >= 3600 && cell < 86400) {
      ndate = cell / 3600 + "小时前";
    }
    // 24小时以上48小时内
    if (cell >= 86400 && cell < 172800) {
      ndate = "昨天";
    }
    // 两天以上7天以内
    if (cell >= 172800 && cell < 604800) {
      ndate = cell / 86400 + "天前";
    }
    if (cell >= 604800) {
      ndate = time.substring(0, 10);
    }
    return ndate;

  }

}
